package route

import (
	"net/http"
)

// HandlerFunc 定义路由处理函数类型
type HandlerFunc func(w http.ResponseWriter, r *http.Request)

// Router 路由管理器
type Router struct {
	routes map[string]map[string]HandlerFunc // method -> path -> handler
}

// NewRouter 创建一个新的路由管理器
func NewRouter() *Router {
	return &Router{
		routes: make(map[string]map[string]HandlerFunc),
	}
}

// AddRoute 添加路由
func (r *Router) AddRoute(method, path string, handler HandlerFunc) {
	if _, ok := r.routes[method]; !ok {
		r.routes[method] = make(map[string]HandlerFunc)
	}
	r.routes[method][path] = handler
}

// GET 添加GET路由
func (r *Router) GET(path string, handler HandlerFunc) {
	r.AddRoute("GET", path, handler)
}

// POST 添加POST路由
func (r *Router) POST(path string, handler HandlerFunc) {
	r.AddRoute("POST", path, handler)
}

// PUT 添加PUT路由
func (r *Router) PUT(path string, handler HandlerFunc) {
	r.AddRoute("PUT", path, handler)
}

// DELETE 添加DELETE路由
func (r *Router) DELETE(path string, handler HandlerFunc) {
	r.AddRoute("DELETE", path, handler)
}

// ServeHTTP 实现http.Handler接口
func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	path := req.URL.Path
	method := req.Method

	// 查找路由
	if handlers, ok := r.routes[method]; ok {
		if handler, exists := handlers[path]; exists {
			handler(w, req)
			return
		}
	}

	// 路由未找到
	http.NotFound(w, req)
}